package com.egdigital.allzic.data.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.egdigital.allzic.data.object.Category;

public class JsonParserCategory {

	// log
	private static final String			TAG					= JsonParserCategory.class.getSimpleName();
	// data
	private static final String			TAG_ID				= "id";
	private static final String			TAG_TITLE			= "title";
	private RequestQueue				mRequestQueue;
	private static JsonParserCategory	mJsonParser;
	private Category					mCategory;
	private JSONArray					mJsonArrayCategory	= null;
	private JsonCallBack				mJsonCallback;

	public static JsonParserCategory getInstance() {
		if (mJsonParser == null) {
			return new JsonParserCategory();
		} else {
			return mJsonParser;
		}
	}

	public void initAndStartRequestQueue() {
		mRequestQueue = VolleyManager.getRequestQueue();
		mRequestQueue.start();
	}

	public void stopRequestQueue() {
		mRequestQueue.stop();
	}

	public void extractJsonObjectData(String url) {
		JsonArrayRequest request = new JsonArrayRequest(url, createMyReqSuccessListener(), createMyReqErrorListener());
		request.setTag(this);
		mRequestQueue.add(request);
		mJsonCallback.downloadStarted();
	}

	protected Response.Listener<JSONArray> createMyReqSuccessListener() {
		return new Response.Listener<JSONArray>() {

			public void onResponse(JSONArray jsonArray) {
				List<Category> listCategory = new ArrayList<Category>();
				try {
					mJsonArrayCategory = jsonArray;
					for (int i = 0; i < mJsonArrayCategory.length(); i++) {
						mJsonCallback.downloadPercent(((i + 1) * 100) / mJsonArrayCategory.length());
						JSONObject jsonNews = mJsonArrayCategory.getJSONObject(i);
						mCategory = new Category(jsonNews.getInt(TAG_ID), jsonNews.getString(TAG_TITLE));
						listCategory.add(mCategory);
					}
				} catch (Exception ex) {
				}
				mJsonCallback.downloadCompleted(listCategory);
			}
		};
	}

	protected Response.ErrorListener createMyReqErrorListener() {
		return new Response.ErrorListener() {

			public void onErrorResponse(VolleyError error) {
				mJsonCallback.downloadEndedWithError(error);
			}
		};
	}

	public void setJsonCallBack(JsonCallBack callback) {
		mJsonCallback = callback;
	}
}
